/**
 * Vue 配置
 * Created by fangsj on 2017/5/22.
 */
import SparkMD5 from 'spark-md5'
async function getOssClient(Vue) {
  return await new Promise((resolve, reject) => {
    if (!Vue.prototype.ossClient) {
      const $script = document.createElement('script')
      $script.setAttribute('id', 'aliyun-oss-sdk')
      global.document.body.appendChild($script)
      $script.src = `https://gosspublic.alicdn.com/aliyun-oss-sdk-6.0.1.min.js`
      $script.onload = () => {
        /* eslint-disable */
        Vue.prototype.ossClient = new OSS({
          region: 'oss-cn-hangzhou',
          accessKeyId: 'LTAIYwqaIFvrhH1y',
          accessKeySecret: 'ViN8ekRSBopLvoWj1ermQF6HGkeXs6',
          bucket: 'keisdom',
          secure: true
        })
        resolve(Vue.prototype.ossClient)
      }
      $script.onerror = () => {
        reject()
      }
    } else {
      resolve(Vue.prototype.ossClient)
    }
  })
}

export default {
  install(Vue, options) {
    Vue.prototype.$oss = (relativeUrl, ossClient) => {
      if (!ossClient) ossClient = Vue.prototype.ossClient
      // return ossClient.signatureUrl(relativeUrl)
      return ossClient._objectUrl(relativeUrl)
    }
    // 初始化一次oss client,如果初始化过一次返回上一次初始化对象
    Vue.prototype.initOssClient = () => {
      return getOssClient(Vue)
    }
    Vue.prototype.uploadForElement = ({
      file,
      data,
      onProgress,
      onSuccess,
      onError
    }) => {
      getOssClient(Vue).then(ossClient => {
        global.ossClient = ossClient
        const objKey = `${data && data.dir ? data.dir : ''}/${uuid(
          false
        )}${file.name.substr(file.name.lastIndexOf('.'))}`
        // 文件是否MD5 加密
        const crypto = data.crypto ? data.crypto : false
        ossClient
          .multipartUpload(objKey, file, {
            progress: async p => {
              onProgress({ percent: p * 100 })
            }
          })
          .then(resp => {
            if (crypto) {
              calcFileMd5(file).then(uniqueId => {
                onSuccess({ name: resp.name, uniqueId })
              })
            } else {
              onSuccess({ name: resp.name })
            }
          })
          .catch(err => {
            onError(err)
          })
      })
    }
  }
}

function calcFileMd5(file) {
  return new Promise((resolve, reject) => {
    let blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice,
      chunkSize = 2097152, // Read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader()
    fileReader.onload = e => {
      spark.append(e.target.result)
      currentChunk++
      if (currentChunk < chunks) {
        loadNext()
      } else {
        resolve(spark.end())
      }
    }
    fileReader.onerror = () => {
      console.warn('oops, something went wrong.')
      reject()
    }
    const loadNext = () => {
      let start = currentChunk * chunkSize,
        end = start + chunkSize >= file.size ? file.size : start + chunkSize
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
    }
    loadNext()
  })
}
